/**
* ShieldJSPage
* @fileOverview 翻页，需要依赖shield.main.js以及tool/doT.js，templ/page.html
* @author kevin
* @email donggongai@126.com
* @version 1.0
* @date 2018-3-16
*/
;(function($){
	/**
	* @author kevin
	* @constructor ShieldJSPage
	* @description 菜单样式
	* @see The <a href="#">kevin</a>
	* @example
	*	$(".nav").ShieldJSPage();
	* @since version 1.0
	*/
	$.fn.ShieldJSPage = function(options){
		debug(this);
		if (this.length > 0) {
			/**
			 * @description {Json} 设置参数选项
			 * @field
			 */
			var options = $.extend({},$.fn.ShieldJSPage.defaults, options);
			/**
			 * @description 处理函数
			 */
			return this.each(function() {
				var thisSelectE = $(this);
				//使用了metadata插件获取元数据
				var o = $.metadata ? $.extend({}, options, thisSelectE.metadata()) : options;
				
				var templData = {}; //模板数据
				templData.pages = [];
				
				var pageUrl = thisSelectE.attr("pageUrl");
				var curPage = parseInt(thisSelectE.attr("curPage")||1); //当前页数,默认1
				var totalPage = parseInt(thisSelectE.attr("totalPage")||0); //总页数,默认0
				var totalCount = parseInt(thisSelectE.attr("totalCount")||0); //总条数,默认0
				var groups = parseInt(thisSelectE.attr("groups")||5); //连续页码个数,默认5
				var curColor = thisSelectE.attr("curColor")||""; //选中项的背景色
				var prev = thisSelectE.attr("prev")||"上一页"; //上一页显示内容，非title
				var next = thisSelectE.attr("next")||"下一页"; //下一页显示内容，非title
				var first = thisSelectE.attr("first")||1; //首页显示内容，非title
				var last = thisSelectE.attr("last")||totalPage; //尾页显示内容，非title
				var target = thisSelectE.attr("target"); //翻页后内容区
				var templid = thisSelectE.attr("templid")||'default'; //模板id
				if (curPage <= 0) {
					curPage = 1;
				}
				//当前页不能超过总页数
				if(curPage > totalPage){
					curPage = totalPage;
				}
				//连续分页个数不能低于0且不能大于总页数
				if(groups < 0){
					groups = 1;
				} else if (groups > totalPage){
					groups = totalPage;
				}
				if (groups > 50){
					groups = 50;
				}
				
				//计算当前组
				var index = totalPage > groups 
				? Math.ceil( (curPage + (groups > 1 ? 1 : 0)) / (groups > 0 ? groups : 1) )
						: 1;
				ShieldJS.debug("分页组："+index+" == "+curPage);
				//计算当前页码组的起始页
				var halve = Math.floor((groups-1)/2) //页码数等分
				,start = index > 1 ? curPage - halve : 1
				,end = index > 1 ? (function(){
					var max = curPage + (groups - halve - 1);
					return max > totalPage ? totalPage : max;
				}()) : groups;
				
				//防止最后一组出现“不规定”的连续页码数
				if(end - start < groups - 1){
					start = end - groups + 1;
				}
				//上一页
				var page = {
						num:0,bgcolor:"",
						/*显示名称*/
						name:"",
						/*样式*/
						classes:"",
						/*背景色*/
						bgcolor:"",title:"",
						prev:false,more:false,curr:false,next:false
				};
				page.num = curPage-1;
				page.prev = true;
				page.name = prev;
				var prevClass = "shield-laypage-prev "
					if (curPage == 1) {
						prevClass += ShieldJS.css.DISABLED;
					}
				page.classes = prevClass;
				templData.pages.push(page);
				//输出首页及左分割符
				if(start > 2 && first != "false"){
					if(groups !== 0){
						var page = {};
						page.num = 1;
						page.name = first;
						page.title = "首页";
						templData.pages.push(page);
					}
					var page = {};
					page.more = true;
					page.classes = "shield-laypage-spr";
					page.name = "&#x2026;"; //…
					templData.pages.push(page);
				}
				
				//输出连续页码
				for(; start <= end; start++){
					var page = {};
					page.num = start;
					page.name = start;
					if(start === curPage){
						page.curr = true;
						page.classes = "shield-laypage-curr";
						page.bgcolor = curColor;
						//当前页
					}
					if (start === 1) {
						page.title = "首页";
					} else if (start === totalPage) {
						page.title = "尾页";
					}
					templData.pages.push(page);
				}
				
				//输出输出右分隔符 & 末页
				if(totalPage > groups && totalPage > end && last != "false"){
					var page = {};
					if (end + 1 < totalPage) {
						page.more = true;
						page.classes = "shield-laypage-spr";
						page.name = "&#x2026;"; //…
						templData.pages.push(page);
					}
					if (groups !== 0) {
						var page = {};
						page.num = totalPage;
						page.name = last;
						page.bgcolor = "";
						page.title = "尾页";
						templData.pages.push(page);
					}
				}
				//下一页
				page = {};
				page.num = curPage+1;
				page.bgcolor = "";
				page.next = true;
				page.name = next;
				var nextClass = "shield-laypage-prev "
					if (curPage == totalPage) {
						nextClass += ShieldJS.css.DISABLED;
					}
				page.classes = nextClass;
				templData.pages.push(page);
				
				var checkedClass = "shield-laypage-curr";
				var eleClass="";
				if (hasAttr(thisSelectE, "disabled")) { //样式追加
					eleClass += ShieldJS.css.DISABLED;
				}
				templData.classes = eleClass;
				//调用模板
				var conText = doT.template(ShieldJS.templ.PAGE[templid])(templData);
				ShieldJS.debug(conText);
				thisSelectE.html(conText);
				function checkpage(pageNum, totalpage) {
					if (pageNum - 1 < 0)
						pageNum = 1;
					if (pageNum - totalpage > 0)
						pageNum = totalpage;
					return pageNum;
				}
				//事件绑定
				thisSelectE.on("click", "a", function() {
					var $this = $(this);
					if (!$this.hasClass(ShieldJS.css.DISABLED)) {
						if (!$this.data("page")) {
							ShieldJS.error("翻页内容缺少data-page属性页码，请检查！"+$this.prop("outerHTML"));
							return false; //true=continue，false=break。 
						}
						var pageNum = parseInt($this.attr("data-page"));
						pageNum = checkpage(pageNum, totalPage);
						ShieldJS.debug("翻页选中==" + pageNum);
						var params = {};
						var checkParams = ShieldJS.HtmlAction.checkAnGetParamSelector($this, params); //参数选择器
						var targetE;
						if (target) {
							targetE = getjQueryObj(target);
						} else {
							var formE = $this.closest('form');
							if (formE.length > 0) { //存在form则提交form
								
//								ShieldJS.form.initOneSubmit(formE, function(targetE) {
//									//ShieldJS.core.bindHtmlAction(targetE); //内部继续绑定,迁移至回调方法中
//									if (o.onSubmit && $.isFunction(o.onSubmit)) {
//										o.onSubmit(targetE);
//                                    }
//								});
								
								var pageNumE = formE.find('.pageNum');
								pageNumE.val(pageNum);
								formE.submit();
								return false; //阻止冒泡
							} else { //否则直接刷新
								targetE = $this.closest('.shield-tab-item.'+ShieldJS.css.SHOW);
							}
						}
						if (targetE.length > 0) {
							if (pageUrl && pageUrl != "demotest") {
								ShieldJS.ajax.get(targetE, pageUrl+pageNum, checkParams, function(){
									targetE.find(".curPage").text(pageNum).val(pageNum);
									ShieldJS.core.bindHtmlAction(targetE); //内部继续绑定,迁移至回调方法中
//									if (o.onSubmit && $.isFunction(o.onSubmit)) {
//										o.onSubmit(targetE);
//                                    }
								});
                            }
						}
					}
					return false; //阻止冒泡
				});
			});
        }
	};
	/**
	* @description {Json} 默认参数
	* @field
	*/
	$.fn.ShieldJSPage.defaults = {
		// 提交后的回调方法
		onSubmit:null
	};
	$.fn.ShieldJSPage.filter = function(dealEle) {
		var showName = "shield-page元素";
		if (dealEle.length > 0) {
			dealEle.each(function() {
				var $this = $(this);
				var formE = $this.closest('form');
				if (formE.length > 0) { //存在form则提交form
					var pageNumE = formE.find('.pageNum');
					if (pageNumE.length == 0) {
						dealEle = dealEle.not($this);
						ShieldJS.error("检测到"+showName+"父类form中没有定义页码存放元素，请在对应元素上添加class为pageNum！"+$this.prop("outerHTML"));
						return false; //true=continue，false=break。 
	                }
				} else {
					if (!hasAttr($this, "pageUrl")) {
						dealEle = dealEle.not($this);
						ShieldJS.error("检测到"+showName+"缺少pageUrl属性（页面链接）也未将"+showName+"以form包裹，请检查！"+$this.prop("outerHTML"));
						return false; //true=continue，false=break。 
					}
				}
				if (!hasAttr($this, "curPage")) {
					dealEle = dealEle.not($this);
					ShieldJS.error("检测到"+showName+"缺少当前页码curPage属性，请检查！"+$this.prop("outerHTML"));
					return false; //true=continue，false=break。 
				}
				if (!hasAttr($this, "totalPage")) {
					dealEle = dealEle.not($this);
					ShieldJS.error("检测到"+showName+"缺少总页数totalPage属性，请检查！"+$this.prop("outerHTML"));
					return false; //true=continue，false=break。 
				}
				if (!hasAttr($this, "totalCount")) {
					dealEle = dealEle.not($this);
					ShieldJS.error("检测到"+showName+"缺少总条数totalCount属性，请检查！"+$this.prop("outerHTML"));
					return false; //true=continue，false=break。 
				}
	        });
		}
		return dealEle;
	}
	/**
	* @description 输出选中对象的个数到控制台
	* @param {jQueryObject} $obj 选中对象
	*/
	function debug($obj) {
		if (window.console && window.console.log)
			window.console.log('ShieldJSPage selection count: ' + $obj.size());
	};
})(jQuery);